﻿#include <errno.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <linux/can/raw.h>

#include "app_can.h"
#include "netcan.h"
#include "main.h"


#undef   DEBUG_LEVEL
#define  DEBUG_LEVEL  5
#include "vdebug.h"



// 接收线程
static void *recv_task(void *param)
{
	int ret;
	fd_set can_set;
	struct can_handle handle;
	struct timeval timeout;
	unsigned int id;
	unsigned char data[32];
	int nbytes;

	int recv_cnt = 0;


	if (tMsg1.can_no == 0)
		ret = netcan_open("can0", tMsg1.can_kbps * 1000, 0, NULL, &handle);
	else if (tMsg1.can_no == 1)
		ret = netcan_open("can1", tMsg1.can_kbps * 1000, 0, NULL, &handle);


	if (ret < 0)
	{
		debug_error("netcan_open(can)\n");
		return (void*)-1;
	}

	while (1)
	{
		FD_ZERO(&can_set);
		FD_SET(handle.socket, &can_set);
		timeout.tv_sec = 0;
		timeout.tv_usec = 10000;

		ret = select(handle.socket+1, &can_set, NULL, NULL, &timeout);
		if (ret == 0)
		{
			// timemout
		}
		else if (ret > 0)
		{
			// 读取can报文
			nbytes = netcan_read(&handle, &id, data, NULL);
			if (nbytes > 0)
			{
				// 调试信息
				// debug_printf("\n");
				printf("<%08d> rx[ 0x%08x ", recv_cnt++, id);
				for (int i = 0; i < nbytes; ++i)
				{
					printf("0x%02x ", data[i]);
				}
				printf("]\n");
			}
		}
	}

	netcan_close(&handle);
	return 0;
}

static pthread_t can_in_thread = 0;
void can_start_input(void *param)
{
	pthread_create(&can_in_thread, NULL, recv_task, param);
}



void can_stop(void)
{
}

